//
//  TokenPriceController.swift
//  SCA
//
//  Created by tjun on 2025/9/27.
//

import UIKit
import SnapKit

class TokenPriceController: BaseController {
    
    private let trendImageView = UIImageView(image: UIImage(named: "green_arrow"))
    private let iconImageView = UIImageView()
    private let iconNameLabel = UILabel(font: UIFontMediumMake(22), textColor: Assets.Color.white)
    private let priceLabel = UILabel(font: UIFontSemiboldMake(36), textColor: Assets.Color.white)
    private let increaseValueLabel = UILabel(font: UIFontMake(16), textColor: .green)
    private let transactionButton = MainButton(type: .system, title: "交易", font: UIFontMediumMake(14), textColor: .white)
    
    private let lastUpdateDateLabel = UILabel(font: UIFontMediumMake(12), textColor: UIColorMake(0x797777))
    private var priceChartView: TokenPriceChartView!
    
    var model: SCAModel? {
        didSet {
            iconImageView.setImage(url: model?.icon)
            iconNameLabel.text = model?.title
            priceLabel.text = model?.price
            increaseValueLabel.text = model?.percent_disp
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationBar.title = "SCA价位"
        
        view.addSubviews(iconImageView, iconNameLabel, priceLabel, trendImageView, increaseValueLabel)
        
        iconImageView.snp.makeConstraints { make in
            make.left.equalTo(AppStyle.margin.left)
            make.top.equalTo(20 + navBarHeight)
            make.width.height.equalTo(40)
        }
        
        iconNameLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImageView.snp.right).offset(14)
            make.centerY.equalTo(iconImageView)
        }
        
        priceLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImageView)
            make.top.equalTo(iconImageView.snp.bottom).offset(6)
        }
        
        trendImageView.snp.makeConstraints { make in
            make.left.equalTo(priceLabel)
            make.top.equalTo(priceLabel.snp.bottom).offset(8)
        }
        
        increaseValueLabel.snp.makeConstraints { make in
            make.left.equalTo(trendImageView.snp.right)
            make.centerY.equalTo(trendImageView)
        }
        
        transactionButton.addTo(self.view)
        transactionButton.addCorner(radius: 5)
        transactionButton.addTarget(self, action: #selector(transactionButtonTapped), for: .touchUpInside)
        transactionButton.sizeToFit()
        transactionButton.snp.makeConstraints { make in
            make.right.equalTo(-AppStyle.margin.right)
            make.width.equalTo(transactionButton.width + 30)
            make.height.equalTo(AppStyle.size.smallButtonHeight.scaled)
            make.centerY.equalTo(priceLabel)
        }
        
        lastUpdateDateLabel.addTo(self.view)
        lastUpdateDateLabel.numberOfLines = 0
        lastUpdateDateLabel.attributedText = lastUpdateDateLabel.text?.titleMargin(3)
        lastUpdateDateLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImageView)
            make.top.equalTo(increaseValueLabel.snp.bottom).offset(30)
        }
        
        let refreshButton = UIButton(type: .system).addTo(self.view)
        refreshButton.addTarget(self, action: #selector(refreshButtonTapped(_ :)), for: .touchUpInside)
        refreshButton.setImage(Assets.Image.tokenPriceRefresh, for: .normal)
        refreshButton.snp.makeConstraints { make in
            make.centerY.equalTo(lastUpdateDateLabel)
            make.right.equalTo(transactionButton).inset(2)
        }
//        
//        priceChartView = TokenPriceChartView(frame: CGRectMake(0, 0, view.width - AppStyle.margin.left * 2, 300))
//        priceChartView.addTo(view)
//        priceChartView.snp.makeConstraints { make in
//            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
//            make.top.equalTo(lastUpdateDateLabel.snp.bottom).offset(30)
//            make.height.equalTo(300)
//        }
        loadData()
    }
    
    
    private func addZRotation(to target: UIView) {
        let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue = CGFloat.pi * 2    // 360°
        rotation.duration = 2.0              // 转一圈需要 2 秒
        rotation.repeatCount = .infinity     // 无限循环
        rotation.isRemovedOnCompletion = false

        target.layer.add(rotation, forKey: "zRotation")
    }
    
    func loadData(complete: (() -> Void)? = nil) {
        HomeService.loadTokensPriceChartData { model, info in
            print("model=\(model), info=\(info)")
 
            var valueArray: [String] = []
            var valueNumberArray: [Double] = []

            var nameArray: [String] = []
            for chartModel in info.datas {
                valueNumberArray.append(Double(chartModel.value) ?? 0)
                valueArray.append("\(chartModel.value)")
                nameArray.append("")
            }
            
            if let maxValue = valueNumberArray.max(),
               let minValue = valueNumberArray.min() {
                
                
                self.priceChartView.maxValue = String(maxValue)
                self.priceChartView.minValue = String(minValue)
    
                print("最大值: \(maxValue), 最小值: \(minValue)")
            }
            
            
            self.priceChartView.valueArray = valueArray
            self.priceChartView.nameArray = nameArray
            self.priceChartView.strokePath()
            self.lastUpdateDateLabel.text = "最后更新:\n" + info.lastUpdated
            complete?()
        }
    }
    
    @objc func refreshButtonTapped(_ button: UIButton) {
        addZRotation(to: button)
        loadData {
            button.layer.removeAllAnimations()
        }
    }
    
    @objc func transactionButtonTapped() {
        
        
    }
    
    
}

//class SCACoinView: UIView {
//

//
//    var model: SCAModel? {
//        didSet {
//            iconImageView.setImage(url: model?.icon)
//            iconNameLabel.text = model?.title
//            priceLabel.text = model?.price
//            increaseValueLabel.text = model?.percent_disp
//        }
//    }
//
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//
//        setSubView()
//    }
//
//    required init?(coder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//
//    func setSubView() {
//
//        backgroundColor = AppStyle.color.background
//
//        addSubviews(iconImageView, iconNameLabel, priceLabel, increaseValueLabel)
//        iconImageView.snp.makeConstraints { make in
//            make.left.equalTo(20)
//            make.centerY.equalToSuperview()
//            make.width.height.equalTo(40)
//        }
//
//        iconNameLabel.snp.makeConstraints { make in
//            make.left.equalTo(iconImageView.snp.right).offset(14)
//            make.centerY.equalTo(iconImageView)
//        }
//
//        priceLabel.snp.makeConstraints { make in
//            make.right.equalTo(-50)
//            make.top.equalTo(iconImageView)
//        }
//
//        increaseValueLabel.snp.makeConstraints { make in
//            make.right.equalTo(priceLabel)
//            make.bottom.equalTo(iconImageView)
//        }
//
//        let arrowImageView = UIImageView(image: UIImage(named: "arrow_icon")).addTo(self)
//        arrowImageView.snp.makeConstraints { make in
//            make.centerY.equalToSuperview()
//            make.right.equalTo(-20)
//        }
//    }
//
//}
